<?php  
add_action( 'widgets_init', 'd_comments' );

function d_comments() {
	register_widget( 'd_comment' );
}

class d_comment extends WP_Widget {
	function d_comment() {
		$widget_ops = array(
            'classname' => 'd_comment',
            'description' => '显示网友最新评论（头像+名称+评论）' );

        parent::__construct( 'd_comment', 'D9-最新评论', $widget_ops, [] );
	}

	function widget($args, $instance) {
		extract( $args );

		$title = apply_filters('widget_name', $instance['title']);
		$limit = $instance['limit'];
		$more = isset($instance['more']) ? $instance['more'] : '';
		$link = isset($instance['link']) ? $instance['link'] : '';

		$mo='';
		if( $more!='' && $link!='' ) $mo='<a class="btn btn-primary" href="'.$link.'">'.$more.'</a>';
		
		echo $before_widget;
		echo $before_title.$mo.$title.$after_title;
		echo '<ul>';
		echo mod_newcomments($limit);
		echo '</ul>';
		echo $after_widget;
	}

	function form($instance) {

?>
		<p>
			<label>
				标题：
				<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $instance['title']; ?>" />
			</label>
		</p>
		<p>
			<label>
				显示数目：
				<input class="widefat" id="<?php echo $this->get_field_id('limit'); ?>" name="<?php echo $this->get_field_name('limit'); ?>" type="number" value="<?php echo $instance['limit']; ?>" />
			</label>
		</p>
<?php
	}
}

function mod_newcomments($limit = 10){
	$output = '';
	$comments = get_comments('number=' . $limit);
	foreach ( $comments as $comment ) {
		$output .= '<li><a href="'.get_permalink($comment->comment_post_ID).'#comments'.'" title="'.$comment->post_title.'上的评论">';
		$output .= get_avatar( $comment->comment_author_email, $size = '36');
		$output .= strip_tags($comment->comment_author).' <span class="muted">'.timeago( $comment->comment_date_gmt ).'说：<br>'.mb_substr(convert_smilies(strip_tags($comment->comment_content)), 0, 40).'</span></a></li>';
	}
	echo $output;
};


?>